package com.itcoon.cloud.framework.security.handler;

import com.itcoon.cloud.framework.ex.errorcode.IErrorCode;
import com.itcoon.cloud.framework.ex.register.IErrorCodeRegister;
import com.itcoon.cloud.framework.security.ex.SecurityResponseEnum;
import com.itcoon.cloud.framework.utils.SpringUtils;
import com.itcoon.cloud.framework.webmvc.response.ApiResponse;
import com.itcoon.cloud.framework.webmvc.utils.ApiResponseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Administrator
 * created in 2021/4/15
 */
public class DefaultAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private static final Logger log = LoggerFactory.getLogger(DefaultAuthenticationEntryPoint.class);

    private final IErrorCodeRegister errorCodeRegister;

    public DefaultAuthenticationEntryPoint(IErrorCodeRegister errorCodeRegister) {
        this.errorCodeRegister = errorCodeRegister;
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) {
        IErrorCode errorCode = SecurityResponseEnum.ACCESS_UNAUTHORIZED;
        if(authException.getErrorCode() == null){
            if(authException instanceof LockedException){
                errorCode = SecurityResponseEnum.USER_LOCKED;
            }else if(authException instanceof DisabledException){
                errorCode = SecurityResponseEnum.USER_DISABLED;
            }
            log.warn("Authorized Failed: reason is {}", authException.getMessage());
        }else{
            log.warn("Authorized Failed: reason is {}", authException.getErrorCode().getMessage());
            errorCode = authException.getErrorCode();
        }
        String message = errorCodeRegister.getMessage(SpringUtils.getApplicationName(), errorCode.getCode());
        ApiResponseUtils.writeJsonResponse(response, ApiResponse.error(errorCode.getCode(), message), HttpServletResponse.SC_UNAUTHORIZED);
    }
}
